package com.huike.clues.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.huike.clues.domain.dto.RoleStatusDto;
import com.huike.clues.mapper.*;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.exception.BaseException;
import com.huike.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.huike.common.annotation.DataScope;
import com.huike.common.constant.UserConstants;
import com.huike.common.core.domain.entity.SysRole;
import com.huike.common.exception.CustomException;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.spring.SpringUtils;
import com.huike.clues.domain.SysRoleDept;
import com.huike.clues.domain.SysRoleMenu;
import com.huike.clues.mapper.SysRoleDeptMapper;
import com.huike.clues.mapper.SysRoleMapper;
import com.huike.clues.mapper.SysRoleMenuMapper;
import com.huike.clues.mapper.SysUserRoleMapper;
import com.huike.clues.service.ISysRoleService;

import javax.annotation.Resource;

/**
 * 角色 业务层处理
 * 
 * 
 */
@Service
public class SysRoleServiceImpl  implements ISysRoleService
{
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysRoleMenuMapper menuMapper;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Resource
    private SysRoleDeptMapper sysRoleDeptMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll()
    {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role)
    {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Integer> selectRoleListByUserId(Long userId)
    {
        return roleMapper.selectRoleListByUserId(userId);
    }
    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(SysRole sysRole) {
        if (sysRole.getMenuIds()!=null&&sysRole.getMenuIds().length>0) {
            sysRoleMenuMapper.deleteRoleMenuByRoleId(sysRole.getRoleId());
            ArrayList<SysRoleMenu> sysRoleMenus = new ArrayList<>();
            Arrays.stream(sysRole.getMenuIds()).peek(o -> sysRoleMenus.add(new SysRoleMenu(sysRole.getRoleId(), o))).collect(Collectors.toList());
            sysRoleMenuMapper.batchRoleMenu(sysRoleMenus);
        }
        if (sysRole.getDeptIds()!=null&&sysRole.getDeptIds().length>0) {
            sysRoleDeptMapper.deleteRoleDeptByRoleId(sysRole.getRoleId());
            ArrayList<SysRoleDept> sysRoleDepts = new ArrayList<>();
            ArrayList<Long> longs = new ArrayList<>();
            List<Long> parentsId=sysDeptMapper.findParentId();
            for (Long menuId : sysRole.getDeptIds()) {
                longs.add(menuId);
                for (Long aLong : parentsId) {
                    if (menuId.equals(aLong)){
                        longs.remove(menuId);
                    }
                }
            }
            longs.stream().peek(o -> sysRoleDepts.add(new SysRoleDept(sysRole.getRoleId(), o))).collect(Collectors.toList());
            if (sysRoleDepts.size()>0) {
                sysRoleDeptMapper.batchRoleDept(sysRoleDepts);
            }
        }
        roleMapper.update(sysRole);
    }

    @Override
    public void deleteById(List roleId) {
        Long row=roleMapper.countUser(roleId);
        if (row>0){
            throw new BaseException("角色有对应的用户不能删除");
        }
        Long[] roleds=new Long[roleId.size()];
        for (int i = 0; i < roleId.size(); i++) {
            roleds[i]=(Long)roleId.get(i);
        }
        sysRoleDeptMapper.deleteRoleDept(roleds);
        sysRoleMenuMapper.deleteRoleMenu(roleds);
        roleMapper.deleteById(roleId);
    }

    @Override
    public SysRole findById(Long roleId) {
        List<Long> roleMenu=sysRoleMenuMapper.findbyRoleId(roleId);
        List<Long> roleDept=sysRoleDeptMapper.findbyRoleId(roleId);
        SysRole sysRole=roleMapper.findById(roleId);
        if (roleMenu.size()>0) {
            sysRole.setMenuIds(roleMenu.toArray(new Long[roleMenu.size()]));
        }
        if (roleDept.size()>0) {
            sysRole.setDeptIds(roleDept.toArray(new Long[roleDept.size()]));
        }
        return sysRole;
    }

    @Override
    public void changeStatus(RoleStatusDto roleStatusDto) {
        Integer row=roleMapper.updateStatus(roleStatusDto);
        if (row==0) {
            throw new BaseException("修改异常");
        }
    }

    @Override
    @Transactional
    public void add(SysRole sysRole) {
        ArrayList<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        sysRole.setDelFlag("0");
        try {
            roleMapper.add(sysRole);
        } catch (Exception e) {
            throw new BaseException(sysRole.getRoleName()+"重复，请重新添加");
        }
        Long[] menuIds = sysRole.getMenuIds();
        if (menuIds.length>0) {
            for (Long menuId : menuIds) {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(sysRole.getRoleId());
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenus.add(sysRoleMenu);
            }
            menuMapper.batchRoleMenu(sysRoleMenus);
        }
    }

}
